﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using DTCash.Redis;
using Uranus.Common;
using Uranus.Service.ContentsService;
using Uranus.Service.ProductService;
using Uranus.Service.UserService;
using Uranus.WeiStationAPI.App_Start;
using Uranus.WeiStationAPI.Common;
using Uranus.WeiStationAPI.Models;

namespace Uranus.WeiStationAPI.Controllers
{
    public class OtherController : BaseController
    {
        /// <summary>
        /// 根据id获取内容管理信息
        /// Date:2017-10-23 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse GetContentsByID()
        {
            string id = GetParmsKey<string>("id");
            int cid;
            if (string.IsNullOrEmpty(id) || !int.TryParse(id, out cid))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            ContentsResponse response = Uranus.Service.Contents.GetContents().SelectContentsByID(new ContentsRequest()
                {
                    Info = new ContentsDTO() { ContentID = cid }
                });
            if (response != null && response.Code == 1)
            {
                resultResPonse.code = 1;
                resultResPonse.data = response.InfoList.Count > 0 ? response.InfoList[0] : null;
                return Send(resultResPonse);
            }
            resultResPonse.code = 2;
            return Send(resultResPonse);
        }

        /// <summary>
        /// 根据产品编号获取合同范本类型 返回所有范本类型配置
        /// Date:2017年11月6日21:16:43
        /// Author:GUO
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse GetContractModelByCode()
        {
            string id = GetParmsKey<string>("id");
            if (string.IsNullOrEmpty(id) || id.Length != 8)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            LoanProductDTO dto = (Service.Product.GetProduct().GetLoanProductByCode(new LoanProductRequest()
            {
                LoanProductDto = new LoanProductDTO()
                {
                    ProductCode = id
                }
            }) ?? new LoanProductResponse()).LoanProductDto;
            object value = ConfigCenterWork.GetConfigValueByOperationType(9);
            if (dto != null && value != null && !string.IsNullOrEmpty(dto.ProductCode))
            {
                string key = string.Empty;
                if (dto.BusinessTypeID == 1)
                {
                    key = "jingying";
                }
                else if (dto.BusinessTypeID == 2)
                {
                    key = "qiche";
                }
                else if (dto.BusinessTypeID == 3)
                {
                    key = "fangwu";
                }
                resultResPonse.code = 1;
                resultResPonse.data = new { key = key, list = value };
            }
            else
            {
                resultResPonse.code = 6;
            }
            return Send(resultResPonse);
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin, EnEncryption = false)]
        public ResultResPonse PreviewGalleryPic()
        {
            if (fileCollection == null || fileCollection.Count == 0 || fileCollection[0] == null)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }

            string fileHost = ConfigurationManager.AppSettings["FileUrl"];
            int w = Validates.GetInt(GetParmsKey<string>("width"));
            if (w == 0)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }

            try
            {
                string extension = Path.GetExtension(fileCollection[0].FileName);

                string savePath = string.Format("/App_Data/ImagePhoto/{0}{1}", Guid.NewGuid().ToString("N"), extension);
                Image image = ImageCommon.GetImageUplaodPhoto(fileCollection[0].InputStream, w, HttpContext.Current.Server.MapPath(savePath));
                byte[] bytes = ImageCommon.GetByteImage(image);
                string filePath = string.Format("/Image/User/{0}/{1}/{2}/{3}/big/{4}{5}", DateTime.Now.Year,
                    DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour,
                    Guid.NewGuid().ToString("N"), extension);
                if (Service.File.GetFile().UpFile(bytes, filePath))
                {
                    image.Dispose();
                    //System.IO.File.Delete(HttpContext.Current.Server.MapPath(savePath));
                    resultResPonse.code = 1;
                    //resultResPonse.data = fileHost + filePath;
                    resultResPonse.data = "http://192.168.20.195:8001/file" + filePath;
                }
                else
                {
                    resultResPonse.code = 5;
                    resultResPonse.data = "上传失败，请重试";
                }
                return Send(resultResPonse);

            }
            catch (Exception ex)
            {
                DTCash.Logger.LogHelper.WriteLogError("用户选择相册相片上传失败", "", ex);
            }

            resultResPonse.code = 2;
            return Send(resultResPonse);
        }

        /// <summary>
        /// 上传头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin, EnEncryption = false)]
        public ResultResPonse UploadUserPhoto()
        {
            if (fileCollection == null || fileCollection.Count == 0 || fileCollection[0] == null)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }

            int w = Validates.GetInt(GetParmsKey<string>("width"));
            if (w == 0)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }

            string fileHost = ConfigurationManager.AppSettings["FileUrl"];
            try
            {
                string extension = Path.GetExtension(fileCollection[0].FileName);
                string savePath = string.Format("/App_Data/ImagePhoto/{0}{1}", Guid.NewGuid().ToString("N"), extension);
                using (Image image = ImageCommon.GetImageUplaodPhoto(fileCollection[0].InputStream, w,
                    HttpContext.Current.Server.MapPath(savePath)))
                {
                    byte[] bytes = ImageCommon.GetByteImage(image);
                    string filePath = string.Format("/Image/User/{0}/{1}/{2}/{3}/big/{4}{5}", DateTime.Now.Year,
                        DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour,
                        Guid.NewGuid().ToString("N"), extension);
                    if (Service.File.GetFile().UpFile(bytes, filePath))
                    {
                        image.Dispose();
                        System.IO.File.Delete(HttpContext.Current.Server.MapPath(savePath));
                        string url = fileHost + filePath;
                        if (Uranus.Service.User.GetUser().UpdateUserPhoto(new UserRequest()
                        {
                            UserDto = new UserDTO()
                            {
                                UserID = UserInfo.UserID,
                                UserPhoto = url
                            }
                        }).Code == 1)
                        {
                            CacheRedis.DelCacheKeys(CacheItem.InitByIdentity(UserInfo.UserID.ToString(), "GetUserByUserID").User.Info);
                            resultResPonse.code = 1;
                            resultResPonse.data = url;
                            return Send(resultResPonse);
                        }
                    }
                    resultResPonse.code = 5;
                    resultResPonse.data = "上传失败，请重试";
                    return Send(resultResPonse);
                }
            }
            catch (Exception ex)
            {
                DTCash.Logger.LogHelper.WriteLogError("用户上传头像出现异常", ex.Message, ex);
            }
            resultResPonse.code = 2;
            return Send(resultResPonse);
        }
    }
}
